/*Copyright 2014 Douglas Soares

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package br.ds.twitter4a.async.oauth;

import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import br.ds.twitter4a.callback.TwitterAccessTokenCallback;
import br.ds.twitter4a.rest.util.TwitterPreferences;
import br.ds.twitter4a.rest.util.TwitterProvider;

/**
 * @author douglas.soares
 * 
 */
public class TwitterAccessTokenTask extends AsyncTask<String, Void, Void> {

    private final Context context;

    private final TwitterAccessTokenCallback callback;

    public TwitterAccessTokenTask(final Context context,
	    TwitterAccessTokenCallback callback) {
	this.context = context;
	this.callback = callback;
    }

    /** {@inheritDoc} */
    @Override
    protected Void doInBackground(final String... params) {
	try {

	    final OAuthService service = TwitterProvider.getoAuthService();

	    // Creating the verifier
	    final Verifier verifier = new Verifier(params[0]);

	    final TwitterPreferences preferences = TwitterPreferences
		    .getInstance(context);

	    // Retrieving the requestToken
	    final Token requestToken = new Token(
		    preferences.retrieveRequestToken(),
		    preferences.retrieveTokenSecret());

	    // Getting access token.
	    final Token accessToken = service.getAccessToken(requestToken,
		    verifier);

	    preferences.updateAccessToken(accessToken.getToken());
	    preferences.updateTokenSecret(accessToken.getSecret());

	    callback.onAccessTokenSaved();
	} catch (final Exception e) {
	    Log.e("", "");
	    callback.onAccessTokenError();
	}
	return null;
    }

}